#!/usr/bin/env bash

#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
# 
#   http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
#


#
# Distributed perftest.
# Runs perftest clients on multiple hosts using ssh.
# 

set -e
usage() {
cat <<EOF
usage: $0 <perftest-args> -- <client-hosts ...> [ --- <broker hosts...> ]
Client & broker hosts can also be set in env vars CLIENTS and BROKERS.

Run perftest clients on the client hosts against brokers on the broker
hosts Clients are assigned to client hosts round robin: publishers
first, then subscribers. If there are multiple brokers (for cluster
tests) clients connect to them round robin.

Broker hosts can be listed with -b in perftest-args or after ---
at the end of the arguments.

Error: $*
EOF
exit 1
}

TESTDIR=${TESTDIR:-$PWD}	# Absolute path to test exes on all hosts.

collect() { eval $COLLECT=\""\$$COLLECT $*"\"; }
NPUBS=1
NSUBS=1
COLLECT=ARGS
while test $# -gt 0; do
    case $1 in
	--publish|--subscribe|--setup|--control) usage "Don't pass perftest action flags: $1" ;;
	--npubs) collect $1 $2; NPUBS=$2; shift 2 ;;
	--nsubs) collect $1 $2; NSUBS=$2; shift 2 ;;
	-s|--summary) collect $1; QUIET=yes; shift 1 ;;
	-b|--broker) BROKERS="$BROKERS $2"; shift 2;;
	--) COLLECT=CLIENTARG; shift ;;
	---) COLLECT=BROKERARG; shift;;
	*) collect $1; shift ;;
    esac
done

CLIENTS=${CLIENTARG:-$CLIENTS}
if [ -z "$CLIENTS" ]; then usage "No client hosts listed after --"; fi
BROKERS=${BROKERARG:-$BROKERS}
if [ -z "$BROKERS" ]; then usage "No brokers specified"; fi

PERFTEST="$TESTDIR/perftest $ARGS"

CLIENTS=($CLIENTS)
BROKERS=($BROKERS)
start() {
    CLIENT=${CLIENTS[i % ${#CLIENTS[*]}]}
    BROKER=${BROKERS[i % ${#BROKERS[*]}]}
    ARGS="$* --broker $BROKER"
    cmd="ssh -n $CLIENT $PERFTEST $ARGS"
    test -z "$QUIET" && echo "Client $i: $cmd"
    $cmd &
}

$PERFTEST --setup -b ${BROKERS[0]}
for (( i=0 ; i < $NPUBS ; ++i)); do start --publish; done
for (( ; i < $NPUBS+$NSUBS ; ++i)); do start --subscribe; done
$PERFTEST --control  -b ${BROKERS[0]}
